package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    public PageInfo selectList(QueryObject qo){
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List list = roleMapper.selectList(qo);

        return new PageInfo(list);

    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Transactional
    @Override
    public void  save(Role role, Long[] ids) {
        roleMapper.insert(role);
        //新增完成之后需要维护中间表之间的关系
        if(ids!=null && ids.length>0)
        for(Long pId:ids){
            roleMapper.insertRelation(role.getId(),pId);
        }
    }

    @Transactional
    @Override
    public void update(Role role, Long[] ids) {
        roleMapper.updateByPrimaryKey(role);
        //更新之后可以把原来selfPermissions删除，然后重新插入即可
        roleMapper.deleteRelation(role.getId());
        //新增完成之后需要维护中间表之间的关系
        if(ids!=null && ids.length>0)
            for(Long pId:ids){
                roleMapper.insertRelation(role.getId(),pId);
            }
    }

    @Override
    public List selectAll() {
        return roleMapper.selectAll();
    }

    @Override
    public List selectByEmpId(Long empId) {
        return roleMapper.selectByEmpId(empId);
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);
        roleMapper.deleteRelation(id);
    }

}
